<?php

namespace app\api\controller;

use app\common\controller\Api;

use think\Db;

/**
 * 微信相关
 */
class Wechats extends Api
{
    protected $noNeedLogin = ['get_access_token', 'getWxInfoTest', 'getWechatScan', 'getWxConfigInfo', 'getWxOpenId', 'getAccessToken', 'send_template_message', 'send_template_message_test'];
    protected $noNeedRight = ['*'];

    protected static $instance;

    public static function instance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new static();
        }
        return self::$instance;
    }

    /**
     * 获取授权token网页授权
     */
    public static function get_access_token($code)
    {
        $wx_token = "";
        if (session('wx_token') && !empty(session('wx_token'))) {
            $wx_token = session("wx_token");
        } else {
            $wechat = config("wechat");
            $urls = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $wechat["AppID"] . "&secret=" . $wechat["AppSecret"];
            $token_data = http_curl($urls);
            dump($token_data);
            if (!empty($token_data)) {
                session("wx_token", $token_data["access_token"], $token_data["expires_in"]);
                $wx_token = $token_data["access_token"];
            }
        }
        return $wx_token;
    }

    /**
     * 获取微信用户信息
     */
    public static function getuserinfo($wx_token)
    {
        $urls = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $wx_token . "&openid=" . config("wechat")["AppID"] . "&lang=zh_CN";
        $token_data = http_curl($urls);
        return $token_data["openid"];
    }

    public static function getWxInfo($code)
    {
        $urls = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . config("wechat")["AppID"] . "&secret=" . config("wechat")["AppSecret"] . "&code=" . $code . "&grant_type=authorization_code";
        $token_data = http_curl($urls);
        if (isset($token_data["openid"])) {
            return $token_data["openid"];
        } else {
            return "";
        }
    }

    public function getWechatScan()
    {
        $url = $this->request->post("url");
        $wechat = config("wechat");
        //获取accesstoken
        $token = get_accesstoken($wechat["AppID"], $wechat["AppSecret"]);
        //获取jsapi_ticket
        $ticket = get_jsapi_ticket($token);

        //整合参数
        $sign_data['noncestr'] = createNoncestr();
        $sign_data['jsapi_ticket'] = $ticket;
        $sign_data['timestamp'] = time();
        $sign_data['url'] = $url;

        //签名
        $signature = getSign($sign_data);

        $scancon['signature'] = $signature;
        $scancon['noncestr'] = $sign_data['noncestr'];
        $scancon['timestamp'] = $sign_data['timestamp'];
        $scancon['appid'] = $wechat["AppID"];
        $scancon['jsApiList'] = ["qrCode", "barCode", "scanQRCode"];

        $this->success("请求成功", $scancon);
    }

    // 获取公众号信息
    public function getWxConfigInfo()
    {
        $this->success("公众号信息", config("wechat"));
    }

    // 获取微信OPENID
    public function getWxOpenId()
    {
        $code = $this->request->post("code");
        if (!empty($code)) {
            $openid = $this->getWxOpenIds($code, config("wechat.AppID"), config("wechat.AppSecret"));
            if (!empty($openid)) {
                $this->success("openid", $openid);
            } else {
                $this->error("获取失败");
            }
        } else {
            $this->error("参数错误");
        }
    }

    // 获取用户微信OPENID
    public function getWxOpenIds($code, $appid, $secret)
    {
        $openid_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $secret . '&code=' . $code . '&grant_type=authorization_code';
        $res = json_decode(file_get_contents($openid_url), true);
        // file_put_contents('./wechats.txt', json_encode($res));
        if (isset($res['openid'])) {

            $info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $res["access_token"] . '&openid=' . $res['openid'] . '⟨=zh_CN';
            $info = json_decode(file_get_contents($info_url), true);
            $data = [
                "openid" => $info["openid"]
            ];
            $check = Db::table("fd_user_wechats")->where($data)->count();
            if (!$check) {
                $data["nickname"] = $info["nickname"];
                $data["headimgurl"] = $info["headimgurl"];
                Db::table("fd_user_wechats")->insert($data);
            }
            return $res['openid'];
        } else {
            return '';
        }
    }

    // 获取 access_token
    public function getAccessToken()
    {
        $wechat = config("wechat");
        $access_token = '';
        if (session('access_token_bd')) {
            $access_token = session('access_token_bd');
        } else {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $wechat["AppID"] . "&secret=" . $wechat["AppSecret"];
            $returnData = $this->http_request($url);
            $access_token = $returnData["access_token"];
            session_write_close();
            session(['name' => 'access_token_bd', 'value' => $access_token, 'expire' => 7200]);
        }
        return $access_token;
    }

    // 发送模板消息
    public function send_template_message($openid, $template_id, $data, $url = "")
    {
        //        $data = array(
        //            'thing4' => array('value' => "王三", 'color' => ''),
        //            'amount6' => array('value' => "10000", 'color' => ''),
        //            'time3' => array('value' => "2016-8-26", 'color' => ''),
        //            'amount1' => array('value' => '9950', 'color' => '')
        //        );
        //        $openid = 'opFhH6lakZrBPLz4o1B1evlSLoyg';
        //        $url = "http://community.fdkj.top";
        $topcolor = "";


        $access_token = $this->getAccessToken();
        $template = $this->setTemplate($openid, $template_id, $data, $url, $topcolor);
        $urls = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;
        $res = $this->http_request($urls, json_encode($template));
        dump($res);
    }

    public function setTemplate($openid, $template_id, $data, $url, $topcolor)
    {
        switch ($template_id) {
            case 1:
                $tpl = "93J-JhCRM4AzCm8NiN4-fgib9ltqcEqUMH8D1EmjPbI"; //商户结算到账通知
                break;
            case 2:
                $tpl = "QYesuW8SEK1pTA6uHVgcpkDbBex0o34tz419D_mau5Y"; //下单成功通知 
                break;
            case 3:
                $tpl = "RfFRMk9c2yos9y2YIvFxGFeF91DPVi-VuT4C59skPns"; //支付成功通知 
                break;
            case 4:
                $tpl = "xXjjLfFkMkkYH_TvLAAdGTOSmCeEDu6ayabUrurR4RM"; //货物签收通知 
                break;
            case 5:
                $tpl = "xJquxj6xF2BwGFc_siiLqpTLYsI0GTC-EvExYut_Biw"; //客户关联成功通知 
                break;
            case 6:
                $tpl = "WhQkvV3wIYJqYoUv5XgyaEhgWTBywU81-rXZXtaDJkk"; //客户需求处理通知 
                break;
            default:
                $tpl = '';
                break;
        }
        if (!$tpl) {
            return '';
        }
        $template = array(
            'touser' => $openid,
            'template_id' => $tpl,
            'url' => $url,
            'topcolor' => $topcolor,
            'data' => $data
        );
        return $template;
    }

    protected function http_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return json_decode($output, true);
    }

    // 发送模板消息
    public function send_template_message_test()
    {
        $data = array(
            'thing4' => array('value' => "王三", 'color' => ''),
            'amount6' => array('value' => "10000", 'color' => ''),
            'time3' => array('value' => "2016-8-26", 'color' => ''),
            'amount1' => array('value' => '9950', 'color' => '')
        );
        $template_id = 1;
        $openid = 'opFhH6lakZrBPLz4o1B1evlSLoyg';
        $url = "http://community.fdkj.top";
        $topcolor = "";


        $access_token = $this->getAccessToken();
        $template = $this->setTemplate($openid, $template_id, $data, $url, $topcolor);
        $urls = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;
        $res = $this->http_request($urls, json_encode($template));
        dump($res);
    }
}
